<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>课程管理</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="课程编号">
          <el-input v-model="searchForm.code" placeholder="请输入课程编号" clearable size="small"></el-input>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input v-model="searchForm.name" placeholder="请输入课程名称" clearable size="small"></el-input>
        </el-form-item>
        <el-form-item label="适用人群">
          <el-select v-model="searchForm.applicablePerson" placeholder="请选择适用人群" clearable size="small">
            <el-option
                v-for="item in crowdOption"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程学科">
          <el-select v-model="searchForm.subject" placeholder="请选择课程学科" clearable size="small">
            <el-option
                v-for="item in xkOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker
              v-model="dateRange"
              size="small"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch" v-hasPermi="'clues:clue:list'">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom: 10px" @click="handleAdd" v-hasPermi="'clues:course:add'">添加
      </el-button>
      <el-button type="danger" style="margin-bottom: 10px; margin-left: 10px" @click="handleBatchDelete"
                 v-hasPermi="'clues:course:remove'"
                 :disabled="multipleSelection.length === 0">批量删除
      </el-button>
      <el-button type="primary" style="margin-bottom: 10px" @click="exportExcel" v-hasPermi="'clues:course:export'">
        导出
      </el-button>

      <el-table :data="pageData.data" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column prop="code" label="课程编号" width="80px"></el-table-column>
        <el-table-column prop="subject" label="课程学科">
          <template slot-scope="scope">
            {{ getDictLabel(scope.row.subject, xkOptions) }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称"></el-table-column>
        <el-table-column prop="price" label="价格(元)"></el-table-column>
        <el-table-column prop="applicablePerson" label="适用人群">
          <template slot-scope="scope">
            {{ getDictLabel(scope.row.applicablePerson, crowdOption) }}
          </template>
        </el-table-column>
        <el-table-column prop="info" label="课程介绍"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="240px">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" v-hasPermi="'clues:course:edit'">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)"
                       v-hasPermi="'clues:course:remove'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageData.pageNo"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.totalCount">
      </el-pagination>

      <el-dialog :title="saveForm.id==null?'新增课程':'修改课程'" :visible.sync="dialogFormVisible">
        <el-form :model="saveForm" :rules="rules" ref="saveForm" label-width="90px" :inline="true">
          <el-form-item label="课程学科" prop="subject">
            <el-select v-model="saveForm.subject" placeholder="请选择课程学科" clearable size="small">
              <el-option
                  v-for="item in xkOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="saveForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="适用人群" prop="applicablePerson">
            <el-select v-model="saveForm.applicablePerson" placeholder="请选择适用人群" clearable size="small">
              <el-option
                  v-for="item in crowdOption"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程价格" prop="price">
            <el-input-number v-model="saveForm.price" autocomplete="off" controls-position="right"></el-input-number>
          </el-form-item>
          <el-form-item label="课程介绍">
            <el-input type="textarea" v-model="saveForm.info" autocomplete="off" style="width:500px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="doSave">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      multipleSelection: [], // 添加这一行用于存储多选数据
      xkOptions: [],
      crowdOption: [],
      dateRange: [],
      //查询的数据模型
      searchForm: {
        //过滤条件
        code: null,
        nane: null,
        subject: null,
        applicablePerson: null,
        beginTime: null,
        endTime: null,

        //分页条件
        pageNo: 1,
        pageSize: 5,
      },
      //分页数据模型
      pageData: {
        data: [], // 分页数据
        pageNo: 1, // 当前页
        pageSize: 5, // 一页的大小
        totalCount: 0, // 总数据量
        totalPageCount: 0, // 总页数
      },
      //控制对话框显示还是隐藏
      dialogFormVisible: false,
      //新增的数据模型
      saveForm: {
        id: null,
        name: null,
        subject: null,
        applicablePerson: null,
        price: null,
        info: null,
      },
      //验证数据模型
      rules: {
        name: [
          {required: true, message: "请输入课程名称！", trigger: "blur"},
        ],
        subject: [
          {required: true, message: "请选择课程学科！", trigger: "blur"},
        ],
        applicablePerson: [
          {required: true, message: "请选择适用人群！", trigger: "blur"},
        ],
        info: [
          {required: true, message: "请输入课程介绍！", trigger: "blur"},
        ],
      },
    };
  },
  created() {
    this.doSearch();
    this.getDictDataxk();
    this.getDictDatarq();
  },
  methods: {
    exportExcel() {
      this.$axios.get('/api/tb/course/export', {
        params: this.searchForm,
        responseType: 'blob' // 关键：指定响应类型为二进制流
      }).then((res) => {
        // 将后台返回的流数据保存到blob中（浏览器提供的一种二进制数据容器，可以理解为 “内存中的临时文件”。）
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        //浏览器会为内存中的 Blob 对象（临时文件）创建一个临时的 URL 地址
        const url = window.URL.createObjectURL(blob)
        //动态创建一个 <a> 标签（链接标签），但不显示在页面上。
        const a = document.createElement('a')
        //将上面生成的临时 URL 赋值给 <a> 标签的 href 属性
        a.href = url
        // 获取文件名（从响应头或默认值）
        console.log("res.header", res.headers);
        const contentDisposition = res.headers['content-disposition']
        let fileName = 'xxx.xlsx'
        if (contentDisposition) {
          // 解析响应头中的文件名（后端需设置正确的header）
          const match = contentDisposition.match(/filename=(.+)/)
          if (match && match[1]) {
            fileName = decodeURIComponent(match[1])
          }
        }
        // 指定下载后的文件名
        a.download = fileName
        // 将<a>标签临时添加到页面
        document.body.appendChild(a)
        // 模拟点击链接，触发下载
        a.click()
        // 释放临时URL，避免内存泄漏
        window.URL.revokeObjectURL(url)
        // 移除临时<a>标签
        document.body.removeChild(a)
        this.$message.success("导出成功");
      }).catch((error) => {
        console.log(error);
        this.$message.error("导出失败");
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    //查询用户信息
    doSearch() {
      //获取开始时间和结束时间
      if (this.dateRange) {
        this.searchForm.beginTime = this.dateRange[0]
        this.searchForm.endTime = this.dateRange[1]
      } else {
        this.searchForm.beginTime = null;
        this.searchForm.endTime = null;
      }
      this.$axios.get("/api/tb/course/list", {params: this.searchForm})
          .then((res) => {
            if (res.data.code == 200) {
              this.pageData.pageNo = res.data.data.current;
              this.pageData.pageSize = res.data.data.size;
              this.pageData.totalCount = res.data.data.total;
              this.pageData.totalPageCount = res.data.data.pages;
              this.pageData.data = res.data.data.records;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },
    //改变每页显示的条数
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.doSearch();
    },
    //改变当前的页码数
    handleCurrentChange(val) {
      this.searchForm.pageNo = val;
      this.doSearch();
    },
    //清空新增表单数据
    reset() {
      this.saveForm = {
        id: null,
        name: null,
        subject: null,
        applicablePerson: null,
        price: null,
        info: null,
      };
    },
    //添加
    handleAdd() {
      //1.清空模型数据
      this.reset();
      //2.显示对话框
      this.dialogFormVisible = true;
    },
    //保存
    doSave() {
      this.$refs["saveForm"].validate((vali) => {
        if (vali) {
          //发送ajax请求
          this.$axios.post("/api/tb/course/save", this.saveForm)
              .then((res) => {
                if (res.data.code == 200) {
                  //1.关闭对话框
                  this.dialogFormVisible = false;
                  //2.友好提示
                  this.$message.success(res.data.msg);
                  //3.刷新表格
                  this.doSearch();
                } else {
                  //1.友好提示
                  this.$message.error(res.data.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
        }
      });
    },
    //编辑
    handleEdit(index, row) {
      //1.清空模型数据
      this.reset();
      //2.查询要修改的数据
      this.$axios.get("/api/tb/course/view/" + row.id).then((res) => {
        if (res.data.code == 200) {
          this.saveForm = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((err) => {
        console.log(err);
      })
      //3.显示对话框
      this.dialogFormVisible = true;
    },
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据');
        return;
      }
      this.$confirm(`确定要删除选中的 ${this.multipleSelection.length} 条数据吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取选中记录的ID数组
        const ids = this.multipleSelection.map(item => item.id);

        // 发送批量删除请求
        this.$axios.delete("/api/tb/course/batchDel", {data: ids})
            .then((res) => {
              if (res.data.code == 200) {
                this.$message.success(res.data.msg);
                // 清空多选
                this.multipleSelection = [];
                // 刷新表格
                this.doSearch();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //删除
    handleDelete(index, row) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //1.发送ajax请求
        // 获取选中记录的ID数组
        this.$axios.delete("/api/tb/course/batchDel", {data: [row.id]}).then((res) => {
          if (res.data.code == 200) {
            //1.友好提示
            this.$message.success(res.data.msg);
            //2.刷新表格
            this.doSearch();
          } else {
            //1.友好提示
            this.$message.error(res.data.msg);
          }
        }).catch((err) => {
          console.log(err);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //根据类型查询字典数据 -课程学科
    // 获取字典数据 学科
    getDictDataxk() {
      // 假设通过API获取字典数据
      this.$axios.get("/api/sys/dict/getDictData?dictType=" + 'course_subject')
          .then((res) => {
            if (res.data.code == 200) {
              this.xkOptions = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },
    //根据类型查询字典数据 -适用人群
    getDictDatarq() {
      // 假设通过API获取字典数据
      this.$axios.get("/api/sys/dict/getDictData?dictType=" + 'applicable_person')
          .then((res) => {
            if (res.data.code == 200) {
              this.crowdOption = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },
    // 根据字典值获取标签文字
    getDictLabel(value, options) {
      if (!value || !options || options.length === 0) {
        return '';
      }
      const dict = options.find(item => item.dictValue === value);
      return dict ? dict.dictLabel : value;
    },
  },
}
</script>

<style scoped>
</style>

